import styles from "./dialog-message.module.scss"
import {useLocation, useParams} from "react-router-dom";
import {useEffect, useState} from "react";
import {Message, MessageDirection, MessageRole, MessageType} from "@/types/chat";
import {DialogMessageItem} from "@/app/components/dialog/dialog-message-item";
import {DialogMessageInput} from "@/app/components/dialog/dialog-message-input";
import {ChatSession, userChatStore} from "@/app/store/chat-store";
import userScrollToBottom from '@/app/hooks/useScrollToBottom';

interface Props {
    id: string,
    title: string
}

export function DialogMessage() {
    const {id} = useParams();
    const location = useLocation();
    const title = location.state?.title || "新的对话";
    const chatStore = userChatStore();
    const currentSession = chatStore.currentSession();
    const [messages, setMessages] = useState<Message[]>([]);
    const {scrollRef, setAutoScroll, scrollToBottom} = userScrollToBottom();

    const fetchDetail = async () => {
        const session = await chatStore.currentSession() as ChatSession;
        setMessages(session.messages);
    }


    // 输入事件
    const onEnter = (value: string) => {
        const newUserMessage = {
            avatar: "/role/headImage.jpg",
            content: value,
            message_type: MessageType.Text,
            time: Date.now(),
            direction: MessageDirection.Send,
            role: MessageRole.user
        };

        const newSystemMessage = {
            avatar: "/role/interview.png",
            // content: "`ChatGPT` 接口尚未对接，暂时还不能回复 **！！！**",
            content: "我是ChatGPT，是一个**AI问答助手**，请问有什么可以帮助您的呢？",
            message_type: MessageType.Text,
            time: Date.now(),
            direction: MessageDirection.Receive,
            role: MessageRole.system
        }
        // 更新组件中的 messages 状态，使用函数式更新来确保状态的一致性
        setMessages(prev => [...prev, newUserMessage]);

        // 更新当前会话中的消息
        chatStore.onSendMessage(newUserMessage);

        setTimeout(() => {
            setMessages(prev => [...prev, newSystemMessage]);
            chatStore.onSendMessage(newSystemMessage);
        }, 1000)

    }

    // 刷新数据
    useEffect(() => {
        fetchDetail(); // 获取会话的消息
    }, [id]);

    const clearContextIndex = (currentSession.clearContextIndex ?? -1) >= 0
        ? currentSession.clearContextIndex
        : -1;

    return (
        <div className={styles.wrapper}>
            <div className={styles.header}>{title}</div>
            <div className={styles.scroll} ref={scrollRef}>
                {messages?.map(
                    (message, index) => {
                        // const shouldShowClearContextDivider = index === clearContextIndex - 1;
                        return <>
                            <DialogMessageItem message={message} key={index} parentRef={scrollRef}/>
                            {/*{shouldShowClearContextDivider && <ClearContextDivider/>}*/}
                        </>
                    })
                }
            </div>
            <DialogMessageInput onEnter={onEnter}/>
        </div>
    );
}

/**
 * 清除上下文对话信息
 * @constructor
 */
function ClearContextDivider() {
    const chatStore = userChatStore();

    return (
        <div
            className={styles["clear-context"]}
            onClick={() =>
                chatStore.updateCurrentSession(
                    (session) => (session.clearContextIndex = undefined),
                )
            }
        >
            <div className={styles["clear-context-tips"]}>上下文已清除</div>
        </div>
    );
}
